package com.groupbuying.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.google.common.base.Strings;
import com.groupbuying.customer.connector.CurrencyFeign;
import com.groupbuying.customer.connector.SysconfigFeign;
import com.groupbuying.customer.connector.WechatAliFeign;
import com.groupbuying.customer.constants.CommonConstants;
import com.groupbuying.customer.constants.CustomerUshopSearchConstants;
import com.groupbuying.customer.constants.CustomerWxinfoRelSearchConstants;
import com.groupbuying.customer.constants.RedisConstants;
import com.groupbuying.customer.domain.*;
import com.groupbuying.customer.dto.CustomerInfoApiDTO;
import com.groupbuying.customer.mq.CustomerMQConfig;
import com.groupbuying.customer.pojo.CustomerEnum;
import com.groupbuying.customer.service.*;
import com.groupbuying.customer.utils.JwtUtils;
import com.groupbuying.customer.utils.MD5Utils;
import com.groupbuying.customer.utils.RedisUtils;
import com.groupbuying.customer.utils.apiresult.ApiResult;
import com.groupbuying.customer.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional(rollbackFor = Exception.class)
public class CustomerMainServiceImpl implements CustomerMainService {
    private Logger log = LoggerFactory.getLogger(CustomerMainServiceImpl.class);
    @Autowired
    private SysconfigFeign sysconfigFeign;
    @Autowired
    private CurrencyFeign currencyFeign;
    @Autowired
    private CustomerUshopService customerUshopService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private CustomerWxinInfoService customerWxinInfoService;
    @Autowired
    private CustomerWxinfoRelService customerWxinfoRelService;
    @Autowired
    private CustomerAccountService customerAccountService;
    @Autowired
    private Producer producer;
    @Autowired
    private WechatAliFeign wechatAliFeign;

    @Override
    public ApiResult customerRegister(Map<String, Object> mapParams) {
        // 解析map参数
        Object tempParam = mapParams.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("captcha");
        String captcha = tempParam == null ? null : tempParam.toString();
        //微信code
        tempParam = mapParams.get("wxCode");
        String wxCode = tempParam == null ? null : tempParam.toString();

        Map result = new HashMap();

        //判断请求参数不为空
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password) || StringUtils.isEmpty(captcha)) {
            return ApiResult.paramIsNull();
        }

        //校验验证码
        //验证码已判定是新用户
        Object obj = redisUtils.getValue(RedisConstants.RDS_APP_REGISTER + mobile);
        if (null == obj || (!captcha.equals(obj.toString()))) {
            redisUtils.delKey(RedisConstants.RDS_REGISTER_TIME + mobile);
            return ApiResult.failure(ApiResultCode.VERIFICATIONCODEERROR, "");
        }

        //先查询微信信息
        Map<String, String> map = wechatAliFeign.getOpenidAndSessionKeyByCode(wxCode, "youdianproductor");
        if (map == null) {
            log.info("map为空");
            return ApiResult.paramIsNull();
        }
        String openId = map.get("openid");
        if (openId == null) {
            log.info("openid为空");
            return ApiResult.paramIsNull();
        }
        Map searchOpenIdMap = new HashMap();
        searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_OPENID, openId);
        List<CustomerWxinfoRelDO> resultList = customerWxinfoRelService.list(searchOpenIdMap);
        CustomerUshopDO customerUshopDO = null;
        if (resultList != null && resultList.size() != 0) {
            //绑定微信关系
            CustomerWxinfoRelDO customerWxinfoRelDO = resultList.get(0);
            customerUshopDO = customerUshopService.get(customerWxinfoRelDO.getCustomerId());
            customerUshopDO.setGmtModified(new Date());
            customerUshopDO.setMobile(mobile);
            customerUshopDO.setPassword(MD5Utils.md5(password));
            customerUshopDO.setMainUuid("");
            customerUshopService.save(customerUshopDO);
        } else {
            //创建用户信息流程
            customerUshopDO = new CustomerUshopDO();
            customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
            customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
            customerUshopDO.setGmtCreate(new Date());
            customerUshopDO.setGmtModified(new Date());
            customerUshopDO.setMobile(mobile);
            customerUshopDO.setPassword(MD5Utils.md5(password));
            customerUshopDO.setMainUuid("");
            customerUshopService.save(customerUshopDO);
            //绑定微信
            if (StringUtils.isNotEmpty(openId)) {
                // 创建微信关系
                CustomerWxinfoRelDO customerWxinfoRelDO = new CustomerWxinfoRelDO();
                customerWxinfoRelDO.setCustomerId(customerUshopDO.getCustomerId());
                customerWxinfoRelDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerWxinfoRelDO.setGmtCreate(new Date());
                customerWxinfoRelDO.setGmtModified(new Date());
                customerWxinfoRelDO.setOpenId(openId);

                customerWxinfoRelService.save(customerWxinfoRelDO);
            }
        }

        //注册成功
        //授权
        try {
            UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
            //过期天数
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);
        } catch (Exception e) {

        }

        // 异步 创建积分账户
        // currencyMQProducer.createCurrencyAccount(customer.getUuid());

        // 同步创建积分账号
        Map searchMap = new HashMap();
        searchMap.put("customerId", customerUshopDO.getCustomerId());
        Map res = currencyFeign.createCurrencyCustomer(searchMap);
        CustomerInfoApiDTO customerInfoApiDTO = new CustomerInfoApiDTO();
        customerInfoApiDTO.setCustomerId(customerUshopDO.getCustomerId());
        customerInfoApiDTO.setCurrencyNumber(new BigDecimal(res.get("useCurrency").toString()));
        if (res.get("password") == null) {
            customerInfoApiDTO.setIsCurrencyPayWord("0");
        } else {
            customerInfoApiDTO.setIsCurrencyPayWord("1");
        }
        result.put("customer", customerInfoApiDTO);


        Map<String, Object> mqParams = new HashMap<>();
        mqParams.put("userName", mobile);
        mqParams.put("mobile", mobile);
        mqParams.put("password", password);

        //TODO:异步通知够样主平台注册用户
        Message message = new Message(CustomerMQConfig.GY_TOPIC, CustomerMQConfig.MOBILE_REGISTERED, JSON.toJSONString(mqParams, SerializerFeature.DisableCircularReferenceDetect).getBytes());
        producer.send(message);


        return ApiResult.success(ApiResultCode.SUCCESS_REGISTER, result);
    }

    /**
     * 优惠买单用，微信注册
     */
    @Override
    public ApiResult customerWXRegister(Map<String, Object> mapParams) {
        //解析map参数
        Object tempParam = mapParams.get("wxCode");
        String wxCode = tempParam == null ? null : tempParam.toString();

        if (StringUtils.isEmpty(wxCode)) {
            return ApiResult.paramIsNull();
        }

        //查询openId
        Map<String, String> map = wechatAliFeign.getOpenidAndSessionKeyByCode(wxCode, "youdianproductor");
        if (map == null) {
            log.info("map为空");
            return ApiResult.paramIsNull();
        }
        String openId = map.get("openid");
        if (openId == null) {
            log.info("openid为空");
            return ApiResult.paramIsNull();
        }

        log.info("优惠买单，微信注册获取的OpenId:{}", openId);
        Map searchMap = new HashMap();
        searchMap.put(CustomerWxinfoRelSearchConstants.SEARCH_OPENID, openId);
        searchMap.put(CustomerWxinfoRelSearchConstants.SEARCH_ISDELETE, CommonConstants.COMMON_FLAG_UNDEL);
        List<CustomerWxinfoRelDO> resultList = customerWxinfoRelService.list(searchMap);

        //传输数据容器
        Map<String, Object> data = new HashMap();

        if (resultList == null || resultList.size() == 0) {
            //注册流程

            //创建子平台账户
            CustomerUshopDO customerUshopDO = new CustomerUshopDO();
            customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
            customerUshopDO.setGmtCreate(new Date());
            customerUshopDO.setGmtModified(new Date());
            customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
            customerUshopDO.setMainUuid("");
            customerUshopService.save(customerUshopDO);

            // 创建微信关系
            CustomerWxinfoRelDO customerWxinfoRelDO_new = new CustomerWxinfoRelDO();
            customerWxinfoRelDO_new.setCustomerId(customerUshopDO.getCustomerId());
            customerWxinfoRelDO_new.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
            customerWxinfoRelDO_new.setGmtCreate(new Date());
            customerWxinfoRelDO_new.setGmtModified(new Date());
            customerWxinfoRelDO_new.setOpenId(openId);
            customerWxinfoRelService.save(customerWxinfoRelDO_new);

            //保存数据存入容器中
//            data.put("customer",customerUshopDO);
//            data.put("wxRel",customerWxinfoRelDO_new);

//            try {
//                sendMsgToMQ(data,CustomerMQConfig.TAG_CUSTOMER_WX_REGISTER_NEW);
//                log.info("用户新增发送到Mq成功，用户ID:{}",customerUshopDO.getCustomerId());
//            } catch (Exception e) {
//                log.error("新增用户发送MQ失败，采用本地直接入库");
//                customerUshopService.save(customerUshopDO);
//                customerWxinfoRelService.save(customerWxinfoRelDO_new);
//            }

            //授权
            try {
                Map result = new HashMap();
                //授权
                UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");//过期天数
                String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
                result.put("token", token);
                if (!Strings.isNullOrEmpty(customerUshopDO.getMobile())) {
                    result.put("mobile", customerUshopDO.getMobile());
                }
                return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
            } catch (Exception err) {
                err.printStackTrace();
                return ApiResult.failure();
            }

        } else {
            //登录
            CustomerWxinfoRelDO customerWxinfoRelDO = resultList.get(0);
            CustomerUshopDO customerUshopDO = customerUshopService.get(customerWxinfoRelDO.getCustomerId());
            //开始登录
            try {
                Map result = new HashMap();
                //授权
                UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");//过期天数
                String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
                result.put("token", token);
                if (!Strings.isNullOrEmpty(customerUshopDO.getMobile())) {
                    result.put("mobile", customerUshopDO.getMobile());
                }
                return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
            } catch (Exception err) {
                err.printStackTrace();
                return ApiResult.failure();
            }
        }
    }

    @Override
    public ApiResult customerLogin(Map<String, Object> mapParams) {
        //解析map参数
        Object tempParam = mapParams.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("wxCode");
        String wxCode = tempParam == null ? null : tempParam.toString();

        //如果获取手机号或密码为空，则返回false
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            return ApiResult.paramIsNull();
        }

        //根据会员,查找主库
        CustomerDO customer = customerService.getCustomerModelByLoginNameOrMobileOrEmail(mobile);
        //查找优店库
        CustomerUshopDO customerUshopDO = customerUshopService.getUshopInfoByMobile(mobile);
        //情况分支，1.主平台和子平台都有
        if (customer != null && customerUshopDO != null) {
            log.error("1.主平台和子平台都有");
            //重新关联
            customerUshopDO.setMainUuid(customer.getUuid());
            if (Strings.isNullOrEmpty(customerUshopDO.getPassword())) {
                customerUshopDO.setPassword(customer.getPassword());
            }

            customerUshopService.update(customerUshopDO);

            //进行优店平台登录流程
            CustomerAccountDO customerAccountDO = customerAccountService.getByCustomerUuid(customer.getUuid());
            return this.uShopLogin(customerAccountDO, customerUshopDO, password, wxCode);
        }

        //情况分支，2.主平台有，子平台没有
        if (customer != null && customerUshopDO == null) {
            log.error("2.主平台有，子平台没有");
            //进行主平台登录流程
            //进行优店平台登录流程
            return this.goyoungLogin(customer, password, wxCode);
        }

        //情况分支，3.主平台没有，子平台有
        if (customer == null && customerUshopDO != null) {
            log.error("3.主平台没有，子平台有");

            //TODO:异步通知主平台创建账号
            Map<String, Object> mqParams = new HashMap<>();
            mqParams.put("userName", mobile);
            mqParams.put("mobile", mobile);
            mqParams.put("password", password);

            Message message = new Message(CustomerMQConfig.GY_TOPIC, CustomerMQConfig.MOBILE_REGISTERED, JSON.toJSONString(mqParams, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            //进行子平台登录
            return this.uShopLogin(null, customerUshopDO, password, wxCode);
        }

        //情况分支，4.主平台和子平台都没有
        if (customer == null && customerUshopDO == null) {
            return ApiResult.success(ApiResultCode.LOGINNAMENOTEXISTS, "");
        }
        return null;
    }

    /**
     * 够样主优店登录逻辑
     */
    public ApiResult uShopLogin(CustomerAccountDO customerAccountDO, CustomerUshopDO customerUshopDO, String password, String wxCode) {
        if (Strings.isNullOrEmpty(customerUshopDO.getPassword())) {
            //部分用户孔直接过
        } else if (!customerUshopDO.getPassword().equals(MD5Utils.md5(password))) {
            // 密码校验
            return ApiResult.success(ApiResultCode.PASSWORDERROR, "");
        }

        //开始登录
        try {
            CustomerWxinfoRelDO customerWxinfoRelDO = customerWxinfoRelService.get(customerUshopDO.getCustomerId());

            //增加openId判断
            Map<String, String> map = wechatAliFeign.getOpenidAndSessionKeyByCode(wxCode, "youdianproductor");
            log.info("查询openid");

            if (map == null) {
                log.info("map为空");
                return ApiResult.paramIsNull();
            }
            String openId = map.get("openid");
            if (openId == null) {
                log.info("openid为空");
                return ApiResult.paramIsNull();
            }
            Map searchOpenIdMap = new HashMap();
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_OPENID, openId);
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_ISDELETE, CommonConstants.COMMON_FLAG_UNDEL);
            List<CustomerWxinfoRelDO> list = customerWxinfoRelService.list(searchOpenIdMap);
            if (list == null || list.size() == 0) {
                //未绑定过微信关系
                //创建微信关系
                CustomerWxinfoRelDO customerWxinfoRelDO_new = new CustomerWxinfoRelDO();
                customerWxinfoRelDO_new.setCustomerId(customerUshopDO.getCustomerId());
                customerWxinfoRelDO_new.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerWxinfoRelDO_new.setGmtCreate(new Date());
                customerWxinfoRelDO_new.setGmtModified(new Date());
                customerWxinfoRelDO_new.setOpenId(openId);
                customerWxinfoRelService.save(customerWxinfoRelDO_new);
            } else {
                //代表当前通过手机号查询的用户，没有绑定支付宝关系
                if (customerWxinfoRelDO == null) {
                    CustomerWxinfoRelDO customerWxinfoRelDOInfo = list.get(0);
                    customerWxinfoRelDO.setCustomerId(customerUshopDO.getCustomerId());
                    customerWxinfoRelService.updateByOpenId(customerWxinfoRelDOInfo);
                } else if (!customerWxinfoRelDO.getOpenId().equals(openId)) {
                    //获取此openid对应的用户
                    CustomerWxinfoRelDO customerWxinfoRelDO_error = list.get(0);
                    CustomerUshopDO customerUshopDO_error = customerUshopService.get(customerWxinfoRelDO_error.getCustomerId());
                    //登录账号与绑定账号不符
                    return ApiResult.failure(-1, "当前微信绑定够样账号为：" + customerUshopDO_error.getMobile() + ",请用该账号登录", "");
                }
            }

            Map result = new HashMap();
            //授权
            UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
            //过期天数
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);

            // 查询积分账户
            Map currencyMap = new HashMap();
            currencyMap.put("customerId", customerUshopDO.getCustomerId());
            currencyMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            Map res = currencyFeign.getCurrencyAccount(currencyMap);

            // 查询有无积分账户
            if (res == null) {
                // 创建积分账户
                Map searchMap = new HashMap();
                searchMap.put(CustomerUshopSearchConstants.SEARCH_CUSTOMERID, customerUshopDO.getCustomerId());
                res = currencyFeign.createCurrencyCustomer(searchMap);
            }

            CustomerInfoApiDTO customerInfoApiDTO = new CustomerInfoApiDTO();
            if (null == customerAccountDO) {
                //新注册用户没有余额
                customerInfoApiDTO.setAccountBalance(Double.valueOf("0.00"));
            } else {
                customerInfoApiDTO.setAccountBalance(customerAccountDO.getNoaccountbalance());
            }
            customerInfoApiDTO.setCustomerId(customerUshopDO.getCustomerId());
            customerInfoApiDTO.setCurrencyNumber(new BigDecimal(res.get("useCurrency").toString()));
            customerInfoApiDTO.setMobile(customerUshopDO.getMobile());
            customerInfoApiDTO.setNickName(customerUshopDO.getMobile());
            if (res.get("password") == null) {
                //未设置积分支付密码
                customerInfoApiDTO.setIsCurrencyPayWord("0");
            } else {
                //已设置积分支付密码
                customerInfoApiDTO.setIsCurrencyPayWord("1");
            }
            result.put("customer", customerInfoApiDTO);
            return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
        } catch (Exception err) {
            err.printStackTrace();
            return ApiResult.failure();
        }
    }

    /**
     * 够样主平台登录逻辑
     */
    public ApiResult goyoungLogin(CustomerDO customer, String password, String wxCode) {
        //检测会员是否冻结
        if (CustomerEnum.CUSTOMER_FROZENSTATE_FROZEN.equals(customer.getFrozenstate())) {
            // 如果会员已经冻结，则返回提示
            return ApiResult.success(ApiResultCode.CUSTOMERFROZEN, "");
        }

        //检测会员是否激活
        if (CustomerEnum.CUSTOMER_ACTIVESTATE_UNACTIVATE.equals(customer.getActivestate())) {
            // 如果会员未激活，则返回提示
            return ApiResult.success(ApiResultCode.CUSTOMERNOACTIVATION, "");
        }

        if (!customer.getPassword().equals(MD5Utils.md5(password))) {
            // 密码校验
            return ApiResult.success(ApiResultCode.PASSWORDERROR, "");
        }

        log.error("goyoungLogin校验密码结束");

        // 开始登录
        try {
            //查询openid关系
            //String openId = customerWxinInfoService.getOpenidByCode(wxCode);
            Map<String, String> map = wechatAliFeign.getOpenidAndSessionKeyByCode(wxCode, "youdianproductor");
            if (map == null) {
                log.info("map为空");
                return ApiResult.paramIsNull();
            }
            String openId = map.get("openid");
            if (openId == null) {
                log.info("openid为空");
                return ApiResult.paramIsNull();
            }
            Map searchOpenIdMap = new HashMap();
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_OPENID, openId);
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_ISDELETE, CommonConstants.COMMON_FLAG_UNDEL);
            List<CustomerWxinfoRelDO> list = customerWxinfoRelService.list(searchOpenIdMap);
            CustomerUshopDO customerUshopDO;

            if (list == null || list.size() == 0) {
                //未绑定过微信关系
                //创建子平台账户
                customerUshopDO = new CustomerUshopDO();
                customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
                customerUshopDO.setGmtCreate(new Date());
                customerUshopDO.setGmtModified(new Date());
                customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerUshopDO.setMobile(customer.getMobile());
                customerUshopDO.setPassword(customer.getPassword());
                customerUshopDO.setMainUuid(customer.getUuid());
                customerUshopService.save(customerUshopDO);

                // 创建微信关系
                CustomerWxinfoRelDO customerWxinfoRelDO_new = new CustomerWxinfoRelDO();
                customerWxinfoRelDO_new.setCustomerId(customerUshopDO.getCustomerId());
                customerWxinfoRelDO_new.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerWxinfoRelDO_new.setGmtCreate(new Date());
                customerWxinfoRelDO_new.setGmtModified(new Date());
                customerWxinfoRelDO_new.setOpenId(openId);
                customerWxinfoRelService.save(customerWxinfoRelDO_new);
            } else {
                //已经绑定过微信关系
                //更新用户信息
                CustomerWxinfoRelDO customerWxinfoRelDO = list.get(0);
                customerUshopDO = customerUshopService.get(customerWxinfoRelDO.getCustomerId());
                customerUshopDO.setMainUuid(customer.getUuid());
                customerUshopDO.setGmtModified(new Date());
                if (Strings.isNullOrEmpty(customerUshopDO.getMobile())) {
                    customerUshopDO.setMobile(customer.getMobile());
                    customerUshopDO.setPassword(customer.getPassword());
                }
                customerUshopService.update(customerUshopDO);
            }

            log.error("开始HashMap");

            Map result = new HashMap();

            //授权
            UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
            //过期天数
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);

            // 查询积分账户
            Map currencyMap = new HashMap();
            currencyMap.put("customerId", customerUshopDO.getCustomerId());
            currencyMap.put("delFlag", CommonConstants.COMMON_FLAG_UNDEL);
            Map res = currencyFeign.getCurrencyAccount(currencyMap);

            // 查询有无积分账户
            if (res == null) {
                // 创建积分账户
                Map searchMap = new HashMap();
                searchMap.put("customerId", customerUshopDO.getCustomerId());
                res = currencyFeign.createCurrencyCustomer(searchMap);
            }

            CustomerInfoApiDTO customerInfoApiDTO = new CustomerInfoApiDTO();


            CustomerAccountDO customerAccountDO = customerAccountService.getByCustomerUuid(customer.getUuid());
            if (null == customerAccountDO) {
                //新注册用户没有余额
                customerInfoApiDTO.setAccountBalance(Double.valueOf("0.00"));
            } else {
                customerInfoApiDTO.setAccountBalance(customerAccountDO.getNoaccountbalance());
            }

            customerInfoApiDTO.setCustomerId(customerUshopDO.getCustomerId());
            customerInfoApiDTO.setCurrencyNumber(new BigDecimal(res.get("useCurrency").toString()));
            customerInfoApiDTO.setMobile(customerUshopDO.getMobile());
            customerInfoApiDTO.setNickName(customerUshopDO.getMobile());
            if (res.get("password") == null) {
                customerInfoApiDTO.setIsCurrencyPayWord("0");
            } else {
                customerInfoApiDTO.setIsCurrencyPayWord("1");
            }
            result.put("customer", customerInfoApiDTO);

            return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
        } catch (Exception err) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            err.printStackTrace();
            return ApiResult.failure();
        }
    }

    @Override
    public ApiResult reSetLoginPassword(Map<String, Object> mapParams) {
        //解析map参数
        Object tempParam = mapParams.get("mobile");
        String mobile = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("password");
        String password = tempParam == null ? null : tempParam.toString();
        tempParam = mapParams.get("passwordAgain");
        String passwordAgain = tempParam == null ? null : tempParam.toString();

        //如果获取手机号或密码为空，则返回false
        if (StringUtils.isEmpty(passwordAgain) || StringUtils.isEmpty(password) || StringUtils.isEmpty(mobile)) {
            return ApiResult.paramIsNull();
        }
        if (!password.equals(passwordAgain)) {
            return ApiResult.failure();
        }

        //重置密码
        CustomerUshopDO customerUshopDO = customerUshopService.getUshopInfoByMobile(mobile);
        customerUshopDO.setPassword(MD5Utils.md5(password));
        customerUshopService.update(customerUshopDO);

        return ApiResult.success();
    }

    /**
     * //红包转用的登录接口
     *
     * @Author Vincentxin
     * @Date 2019/12/9 15:20
     * @param params
     * @return com.groupbuying.customer.utils.apiresult.ApiResult
     **/
    @Override
    public ApiResult redPacketRegister(Map<String, Object> params) {
        //解析参数
        Object tempParam = params.get("password");
        String passwords = tempParam == null ? null : tempParam.toString();
        tempParam = params.get("passwordAgain");
        String passwordAgain = tempParam == null ? null : tempParam.toString();
        tempParam = params.get("encryptedData");
        String encryptedData = tempParam == null ? null : tempParam.toString();
        tempParam = params.get("iv");
        String iv = tempParam == null ? null : tempParam.toString();
        tempParam = params.get("code");
        String code = tempParam == null ? null : tempParam.toString();
        //传入参数不能为空
        if (StringUtils.isEmpty(encryptedData) || StringUtils.isEmpty(iv) || StringUtils.isEmpty(code) ) {
            log.error("参数不能为空");
            return ApiResult.paramIsNull();
        }
//        if (MD5Utils.md5(passwords).equals(MD5Utils.md5(passwordAgain))) {
////            log.error("两次密码不一致");
////            return ApiResult.failure(ApiResultCode.PASSWORDERROR, "");
////        }
//        String password = MD5Utils.md5(passwords);
        //解密
        Map<String, String> decryptData = wechatAliFeign.decryptData(encryptedData, iv, code, "youdianproductor");
        if (decryptData == null || decryptData.size() < 2) {
            return ApiResult.failure(ApiResultCode.AUTHORIZATIONFAILURE, "授权信息解密失败");
        }
        //获取解密手机号
        String mobile = decryptData.get("phoneNumber");
        String openId = decryptData.get("openid");
        Map<String, Object> mqParams = new HashMap<>();


        List<CustomerDO> customers = customerService.getCustomerByMobile(mobile);
        //判断老够样有会员注册的情况
        if (customers.size() > 0) {
            CustomerDO customer = customers.get(0);
            //检测会员是否冻结
            if (CustomerEnum.CUSTOMER_FROZENSTATE_FROZEN.equals(customer.getFrozenstate())) {
                // 如果会员已经冻结，则返回提示
                return ApiResult.success(ApiResultCode.CUSTOMERFROZEN, "");
            }

            //检测会员是否激活
            if (CustomerEnum.CUSTOMER_ACTIVESTATE_UNACTIVATE.equals(customer.getActivestate())) {
                // 如果会员未激活，则返回提示
                return ApiResult.success(ApiResultCode.CUSTOMERNOACTIVATION, "");
            }
            //登录返回token
            try {
                Map result = new HashMap();
                UserToken userToken = new UserToken(customer.getMobile(), customer.getUuid(), "");
                String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
                result.put("token", token);
                result.put("mobile", mobile);
                log.info("登录成功");
                return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
            } catch (Exception e) {
                log.error("登录失败");
                return ApiResult.failure(ApiResultCode.FAILURE);
            }
        }

        List<CustomerUshopDO> customerUshops = customerUshopService.getCustomerByMobile(mobile);
        CustomerUshopDO customerUshopDO = new CustomerUshopDO();
        //判断优店没有注册的情况
        if (customerUshops.size() == 0) {
            Map searchOpenIdMap = new HashMap();
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_OPENID, openId);
            searchOpenIdMap.put(CustomerWxinfoRelSearchConstants.SEARCH_ISDELETE, CommonConstants.COMMON_FLAG_UNDEL);
            List<CustomerWxinfoRelDO> list = customerWxinfoRelService.list(searchOpenIdMap);

            if (list.size() == 0) {
                //未绑定过微信关系
                //创建微信关系
                customerUshopDO.setCustomerId(sysconfigFeign.getCustomerID());
                customerUshopDO.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerUshopDO.setGmtCreate(new Date());
                customerUshopDO.setGmtModified(new Date());
                customerUshopDO.setMobile(mobile);
                customerUshopDO.setPassword(MD5Utils.md5(mobile.substring(mobile.length()-4)));
                customerUshopDO.setMainUuid("");
                customerUshopService.save(customerUshopDO);

                CustomerWxinfoRelDO customerWxinfoRelDO_new = new CustomerWxinfoRelDO();
                customerWxinfoRelDO_new.setCustomerId(customerUshopDO.getCustomerId());
                customerWxinfoRelDO_new.setIsDelete(CommonConstants.COMMON_FLAG_UNDEL);
                customerWxinfoRelDO_new.setGmtCreate(new Date());
                customerWxinfoRelDO_new.setGmtModified(new Date());
                customerWxinfoRelDO_new.setOpenId(openId);
                customerWxinfoRelService.save(customerWxinfoRelDO_new);
            } else {
                CustomerWxinfoRelDO customerWxinfoRelDOInfo = list.get(0);
                customerUshopDO = customerUshopService.get(customerWxinfoRelDOInfo.getCustomerId());
                customerUshopDO.setMobile(mobile);
                customerUshopService.update(customerUshopDO);
            }
        } else {
            customerUshopDO = customerUshops.get(0);
        }

        //发送mq到老够样
        try {
            mqParams.put("userName", mobile);
            mqParams.put("mobile", mobile);
            mqParams.put("password", mobile.substring(mobile.length()-6));
            Message message = new Message(CustomerMQConfig.GY_TOPIC, CustomerMQConfig.MOBILE_REGISTERED, JSON.toJSONString(mqParams, SerializerFeature.DisableCircularReferenceDetect).getBytes());
            producer.send(message);
            log.info("mq发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("mq发送失败：{}",e.getMessage());
//            return ApiResult.failure(ApiResultCode.FAILURE);
        }
        //登录返回token
        try {
            Map result = new HashMap();
            UserToken userToken = new UserToken(customerUshopDO.getMobile(), customerUshopDO.getCustomerId(), "");
            String token = JwtUtils.generateToken(userToken, CommonConstants.COMMON_TOKEN_DAY * 24 * 60 * 60 * 1000);
            result.put("token", token);
            result.put("mobile", mobile);
            log.info("登录成功");
            return ApiResult.success(ApiResultCode.SUCCESS_LOGIN, result);
        } catch (Exception e) {
            log.error("登录失败");
            return ApiResult.failure(ApiResultCode.FAILURE);
        }
    }

    /**
     * 发送的用户中心消费模块的工具方法。
     *
     * @param obj 消息传递对象
     * @Param tag 消息队列tag
     */
    private void sendMsgToMQ(Object obj, String tag) throws Exception {
        //创建子账号平台
        Message message = new Message(CustomerMQConfig.TOPIC, tag,
                JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect).getBytes());
        producer.send(message);
    }
}
